#!/bin/bash
#
# Init file for LuoYun web server daemon
#
# chkconfig: 2345 90 25
# description: LuoYun web server daemon
#
# processname: python
# TOPDIR: /opt/LuoYun/web
# config: ${TOPDIR}/luoyun.cfg
# pidfile:

LUOYUN_TOP_DIR=/opt/LuoYun
prog="lyweb"
OPTIONS=
LYWEBD="python ${OPTIONS} ${LUOYUN_TOP_DIR}/web/site.py"
LYWEBDLOG="${LUOYUN_TOP_DIR}/logs/luoyun.tornado.log"
NGINX="$(which nginx)"
PID_FILE="/var/run/lyweb.pid"

failure()
{
    local rc=$?
    echo " FAILED "
    return $rc
}

success()
{
    echo "  OK  "
    return 0
}

checkdb()
{
    su postgres -c "psql -l -U postgres &> /dev/null"
    if [ $? -ne 0 ]; then
        echo "query postgresql failed. Will check again in 10 seconds..."
        sleep 10
        su postgres -c "psql -l &> /dev/null"
        [ $? -ne 0 ] && echo "query postgresql failed" && exit 1
    fi
}

startnginx()
{
    [ -f "/var/run/nginx.pid" ] || $NGINX
    if [ $? -ne 0 ]; then
        echo "start nginx failed"
        exit 2
    fi
}

stopnginx()
{
    [ -f "/var/run/nginx.pid" ] || return 0
    $NGINX -s stop
    if [ $? -ne 0 ]; then
        echo "stop nginx failed"
    fi
}

start()
{
    if [ -f $PID_FILE ]; then

        num=0

        for pid in $(cat $PID_FILE); do

            kill -s 0 $pid > /dev/null 2>&1

            if [ $? -eq 0 ]; then
                echo "$prog($pid) is started already"
                ((num+=1))
            fi

        done

        if [ $num -gt 0 ]; then
            echo "quit now"
            return
        fi

    fi

    checkdb
    startnginx

    echo -n $"Starting $prog: "
    $LYWEBD >> $LYWEBDLOG 2>&1 &
    RETVAL=$?
    [ "$RETVAL" = 0 ] && success && return 0 || failure
    echo "Please check $LYWEBDLOG"
    return $RETVAL
}


stop()
{
    if [ -f $PID_FILE ]; then

        echo $"Stopping $prog: "

        for pid in $(cat $PID_FILE); do

            kill -s 0 $pid > /dev/null 2>&1

            if [ $? -eq 0 ]; then
                kill $pid && success || failure
            else
                echo "$prog($pid) was not exist"
            fi

        done

        /bin/rm $PID_FILE

        return 0

    else

        echo "$prog was not running now"

    fi

    stopnginx

    RETVAL=$?

    return $RETVAL
}


status()
{

    if [ -f $PID_FILE ]; then

        for pid in $(cat $PID_FILE); do

            kill -s 0 $pid > /dev/null 2>&1

            if [ $? -eq 0 ]; then
                echo "$prog($pid) is running"
            else
                echo "$prog($pid) was not exist"
            fi

        done

        return 0

    else

        echo "$prog was not running now"

    fi
}


case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        stop
        start
        ;;
    status)
        status
        RETVAL=$?
        ;;
    *)
        echo $"Usage: $0 {start|stop|restart|status}"
        RETVAL=1
esac
exit $RETVAL
